/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Action;

import Forms.UploadForm;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

/**
 *
 * @author Antonio
 */
public class UploadAction extends Action {

    @Override
    public ActionForward execute(ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {

        if (form instanceof UploadForm) {
            UploadForm theForm = (UploadForm) form;

            // mostramos los parametros del fichero
            FormFile theFile = theForm.getTheFile();
            String contentType = theFile.getContentType();
            String fileName = theFile.getFileName();
            int fileSize = theFile.getFileSize();
            byte[] fileData = theFile.getFileData();
            String data = "";
            System.out.println("Tipo: " + contentType);
            System.out.println("Nombre: " + fileName);
            System.out.println("Tamano: " + fileSize);


            //guarda los datos del fichero
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            InputStream stream = theFile.getInputStream();

            // solo si el archivo es de menos de 4MB
            if (fileSize < (4 * 1024000)) {
                byte[] buffer = new byte[8192];
                int bytesLeidos = 0;
                while ((bytesLeidos = stream.read(buffer, 0, 8192)) != -1) {
                    baos.write(buffer, 0, bytesLeidos);
                }
                data = new String(baos.toByteArray());
            } else {
                data = new String("Fichero de más de 4MB: no pudo almacenarse." +
                        " Tamano del fichero: " + fileSize + " bytes.");
            }


            return mapping.findForward("ok");
        }
        // solo si no lee un UploadForm
        return null;
    }
}
